from datetime import datetime
from typing import Optional

from pydantic import EmailStr, field_serializer, Field as PydanticField, BaseModel
from sqlalchemy import Integer, Column
from sqlmodel import Field

from src.base.beans import PageParam
from src.base.constants import phone_pattern, ip_pattern, datetime_pattern
from src.base.enums import SexType
from src.domain.base_model import TenantModel
from src.utils.common_utils import serialize_datetime


class SysUserBase(TenantModel):
    user_id: Optional[int] = Field(default=None, primary_key=True, description="用户序号",
                                   sa_column_kwargs={"comment": "用户序号"})
    user_name: Optional[str] = Field(default=None, description="用户名称", sa_column_kwargs={"comment": "用户名称"})
    password: Optional[str] = Field(default=None, description="用户密码", sa_column_kwargs={"comment": "用户密码"})
    nick_name: Optional[str] = Field(default=None, description="用户昵称", sa_column_kwargs={"comment": "用户昵称"})
    email: Optional[EmailStr] = Field(default=None, description="用户邮箱", sa_column_kwargs={"comment": "用户邮箱"})
    phone: Optional[str] = Field(default=None, description="手机号码", regex=phone_pattern,
                                 sa_column_kwargs={"comment": "手机号码"})
    sex: Optional[SexType] = Field(default=None, description="用户性别", sa_type=Integer,
                                   sa_column_kwargs={"comment": "用户性别", "server_default": "0"})
    avatar: Optional[str] = Field(default=None, description="用户头像", sa_column_kwargs={"comment": "用户头像"})
    user_type: Optional[str] = Field(default=None, description="用户类型", sa_column_kwargs={"comment": "用户类型"})
    last_login_time: Optional[datetime] = Field(default=None, description="最后登录时间",
                                                sa_column_kwargs={"comment": "最后登录时间"})
    login_ip: Optional[str] = Field(default=None, description="登录IP", regex=ip_pattern,
                                    sa_column_kwargs={"comment": "登录IP"})

    dept_id: Optional[str] = Field(default=None, description="部门序号", sa_column_kwargs={"comment": "部门序号"})
    post_id: Optional[str] = Field(default=None, description="岗位序号", sa_column_kwargs={"comment": "岗位序号"})

    @field_serializer("last_login_time")
    def serialize_user_datetime(self, value: Optional[datetime], _info):
        return serialize_datetime(value, datetime_pattern)


class SysUser(SysUserBase, table=True):
    __tablename__ = "sys_user"
    # extend_existing ： 表结构已存在，不需要创建
    __table_args__ = {'extend_existing': True, 'comment': '用户表'}


class SysUserReq(SysUserBase, PageParam):
    pass


class SysUserResp(SysUserBase):
    roleCodes: Optional[list[str]] = Field(default=None, description="角色序号", sa_column=Column())
    dept_name: Optional[str] = Field(default=None, description="部门名称", )
    post_name: Optional[str] = Field(default=None, description="岗位名称", )
